// Chromium project main.go
package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"os/exec"
	//"strings"
	"github.com/hailiang/socks"
	"github.com/polaris1119/goconfig/config"
)


func main() {
	c,err := config.ReadDefault("config.ini")

	if err != nil {
		fmt.Println("读取配置文件错误",err)
	}

	proxy,_ := c.Bool("DEFAULT","proxy")
	host,_ := c.String("DEFAULT","host")
	port,_ := c.String("DEFAULT","port")
	verUrl,_ := c.String("DEFAULT","verUrl")

	httpClient := &http.Client{}

	if proxy == true {
		//链接shadowSocks 代理
		dialSocksProxy := socks.DialSocksProxy(socks.SOCKS5, host+":"+port)
		tr := &http.Transport{Dial: dialSocksProxy}
		httpClient = &http.Client{Transport: tr}

	}

	resp, err := httpClient.Get(verUrl)
	if err != nil {
		fmt.Println("获取版本信息错误 或代理链接错误")
		return
	}

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}

	ver := string(body)

	fmt.Println("即将下载版本", string(ver))

	file_src := "http://commondatastorage.googleapis.com/chromium-browser-snapshots/Win/" + string(ver) + "/mini_installer.exe"

	fmt.Println(string(file_src))

	r, err := httpClient.Get(file_src)
	w, err := os.Create("mini_installer.exe")

	//按百分比下载
	length := r.ContentLength
	next_length := length / 100
	now_length := int64(0)
	for i := int64(0); i <= 100; i++ {
		if i != 100 {
			now_length += next_length
			io.CopyN(w, r.Body, next_length)
		} else if i == 100 {
			now_length += length % next_length
			io.CopyN(w, r.Body, length%next_length)
		}

		fmt.Println("下载进度:", i, "%")
	}
	fmt.Println("下载完成,正在安装")

	cmd := exec.Command("./mini_installer.exe")
	cmd.Start()
	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("安装完成")
}

func download(){

}
